﻿using System;
using System.Data;
using System.Windows.Forms;
using Util.Database;


namespace ConfigureNZBLoader
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Open existing DB
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openDBToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == ofd.ShowDialog())
            {
                openDB(ofd.FileName);
            }
        }


        /// <summary>
        /// Create new DB
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newDBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == svd.ShowDialog())
            {
                System.IO.File.Delete(svd.FileName);

                openDB(svd.FileName);
            }
        }


        /// <summary>
        /// Opens the DB and initializes the TreeView control
        /// </summary>
        /// <param name="filename"></param>
        private void openDB(string filename)
        {
            if (DB.IsOpen())
            {
                DB.Close();
            }

            DB.Open(System.Configuration.ConfigurationSettings.AppSettings["DBProvider"], string.Format("Data Source=\"{0}\"", filename));

            tvMain.Nodes.Clear();
            tvMain_AfterSelect(tvMain, null); //Resets the right side of the SplitContainer control

            using (IDbCommand cmd = DB.CreateCommand())
            {
                TreeNode Feeds = new TreeNode("Feeds", 1, 1);
                Feeds.ContextMenuStrip = menuContextNew;
                Feeds.Tag = new TreeItemTags.Feed(0);
                cmd.CommandText = "select * from feed";
                using (IDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        TreeNode t2 = new TreeNode(dr["NAME"].ToString(), 1, 1);
                        t2.ContextMenuStrip = menuContextDelete;
                        t2.Tag = new TreeItemTags.Feed((long)dr["ID"]);
                        Feeds.Nodes.Add(t2);
                    }
                }
                tvMain.Nodes.Add(Feeds);


                TreeNode Shows = new TreeNode("Shows", 2, 2);
                Shows.ContextMenuStrip = menuContextNew;
                Shows.Tag = new TreeItemTags.Show(0);
                cmd.CommandText = "select * from show";
                using (IDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        long ShowId = (long)dr["ID"];

                        TreeNode t2 = new TreeNode(dr["NAME"].ToString(), 2, 2);
                        t2.Tag = new TreeItemTags.Show(ShowId);
                        t2.ContextMenuStrip = menuContextDelete;

                        TreeNode Requests = new TreeNode("Requests");
                        Requests.Tag = new TreeItemTags.DownloadRequest(0, ShowId);
                        Requests.ContextMenuStrip = menuContextNew;
                        using (IDbCommand cmd2 = DB.CreateCommand())
                        {
                            cmd2.CommandText = "select * from request where id_show=?";
                            IDataParameter par = cmd2.CreateParameter();
                            par.Value = ShowId;
                            cmd2.Parameters.Add(par);
                            using (IDataReader dr2 = cmd2.ExecuteReader())
                            {
                                while (dr2.Read())
                                {
                                    TreeNode t3;
                                    long Season = (long)dr2["SEASON"];
                                    long Episode = (long)dr2["EPISODE"];
                                    if (Season == 0 && Episode == 0)
                                    {
                                        t3 = new TreeNode("All Seasons/Episodes");
                                    }
                                    else if (Episode == 0)
                                    {
                                        t3 = new TreeNode("Season " + Season.ToString());
                                    }
                                    else
                                    {
                                        t3 = new TreeNode("Season " + Season.ToString() + " Episode " + Episode.ToString());
                                    }
                                    t3.Tag = new TreeItemTags.DownloadRequest((long)dr2["ID"], ShowId);
                                    t3.ContextMenuStrip = menuContextDelete;
                                    Requests.Nodes.Add(t3);
                                }
                            }
                        }
                        t2.Nodes.Add(Requests);


                        TreeNode AlreadyDownloaded = new TreeNode("Already downloaded");
                        AlreadyDownloaded.Tag = new TreeItemTags.DownloadedEpisode(0, ShowId);
                        AlreadyDownloaded.ContextMenuStrip = menuContextNew;
                        using (IDbCommand cmd2 = DB.CreateCommand())
                        {
                            cmd2.CommandText = "select * from downloaded where id_show=?";
                            IDataParameter par = cmd2.CreateParameter();
                            par.Value = ShowId;
                            cmd2.Parameters.Add(par);
                            using (IDataReader dr2 = cmd2.ExecuteReader())
                            {
                                while (dr2.Read())
                                {
                                    long Season = (long)dr2["SEASON"];
                                    long Episode = (long)dr2["EPISODE"];
                                    TreeNode t3 = new TreeNode("Season " + Season.ToString() + " Episode " + Episode.ToString());
                                    t3.Tag = new TreeItemTags.DownloadedEpisode((long)dr2["ID"], ShowId);
                                    t3.ContextMenuStrip = menuContextDelete;
                                    AlreadyDownloaded.Nodes.Add(t3);
                                }
                            }
                        }
                        t2.Nodes.Add(AlreadyDownloaded);

                        Shows.Nodes.Add(t2);
                    }
                }
                tvMain.Nodes.Add(Shows);

                TreeNode Properties = new TreeNode("Properties");
                Properties.Tag = new TreeItemTags.Properties();
                tvMain.Nodes.Add(Properties);
            }

            toolStripStatusLabel1.Text = filename;
            splitContainer1.Visible = true;
        }


        /// <summary>
        /// Cleanup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (DB.IsOpen())
            {
                DB.Close();
            }
        }

        /// <summary>
        /// Update the display of the right side, load the correct control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvMain_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (splitContainer1.Panel2.Controls.Count > 0)
            {
                ((EditControls.BaseEditControl)splitContainer1.Panel2.Controls[0]).ItemChanged -= new ConfigureNZBLoader.EditControls.BaseEditControl.ChangedEventHandler(ctrl_ItemChanged);
                splitContainer1.Panel2.Controls.Clear();
            }

            if (tvMain.SelectedNode != null)
            {
                EditControls.BaseEditControl ctrl = ((TreeItemTags.BaseTreeItemTag)tvMain.SelectedNode.Tag).EditControl;
                if (ctrl != null)
                {
                    ctrl.ItemChanged += new ConfigureNZBLoader.EditControls.BaseEditControl.ChangedEventHandler(ctrl_ItemChanged);

                    splitContainer1.Panel2.Controls.Add(ctrl);
                    ctrl.Dock = DockStyle.Fill;
                }
            }
        }

        /// <summary>
        /// Update the text in the treeview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="NewText"></param>
        void ctrl_ItemChanged(object sender, string NewText)
        {
            if (tvMain.SelectedNode != null)
            {
                tvMain.SelectedNode.Text = NewText;
            }
        }

        private void newMenuItem_Click(object sender, EventArgs e)
        {
            TreeItemTags.BaseTreeItemTag ti = (TreeItemTags.BaseTreeItemTag)tvMain.SelectedNode.Tag;
            if (ti.canCreate())
            {
                TreeNode t = ti.CreateNew(menuContextNew, menuContextDelete);
                tvMain.SelectedNode.Nodes.Add(t);
                tvMain.SelectedNode = t;
            }
        }

        private void deleteMenuItem_Click(object sender, EventArgs e)
        {
            TreeItemTags.BaseTreeItemTag ti = (TreeItemTags.BaseTreeItemTag)tvMain.SelectedNode.Tag;
            if (ti.canDelete())
            {
                if (MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    ti.Delete();
                    tvMain.SelectedNode.Parent.Nodes.Remove(tvMain.SelectedNode);
                }
            }
        }

        /// <summary>
        /// Handling of the DEL key
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvMain_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete && !e.Alt && !e.Control)
            {
                deleteMenuItem_Click(null, null);
                e.Handled = true;
            }
        }
    }
}
